package comparable.demo;

import java.util.Arrays;

class Stuedent implements Comparable<Stuedent>{
    public String name;
    public int age;

    public Stuedent(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //根据年龄比较
    @Override
    public int compareTo(Stuedent o) {
//        return this.age - o.age;
        return this.name.compareTo(o.name);
    }

    @Override
    public String toString() {
        return "Stuedent{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


public class Test {
    public static void main(String[] args) {
        Stuedent[] stuedents = new Stuedent[3];
        stuedents[0] = new Stuedent("lisi",11);
        stuedents[1] = new Stuedent("zhangsan",32);
        stuedents[2] = new Stuedent("ww",22);
        System.out.println("排序前：" + Arrays.toString(stuedents));
        AgeComparator ageComparator = new AgeComparator();
        Arrays.sort(stuedents,ageComparator);
        System.out.println("排序后：" + Arrays.toString(stuedents));
    }

    //冒泡排序实现
    public static void mySort(Comparable[] comparables){
        for (int i = 0; i < comparables.length - 1; i++) {
            for (int j = 0; j < comparables.length - i - 1; j++) {
                if (comparables[j].compareTo(comparables[j+1]) > 0){
                    Comparable tmp = comparables[j];
                    comparables[j] = comparables[j+1];
                    comparables[j+1] = tmp;
                }
            }
        }
    }

    public static void main2(String[] args) {
        Stuedent[] stuedents = new Stuedent[3];
        stuedents[0] = new Stuedent("lisi",11);
        stuedents[1] = new Stuedent("zhangsan",32);
        stuedents[2] = new Stuedent("ww",22);
        System.out.println("排序前：" + Arrays.toString(stuedents));
        mySort(stuedents);
        System.out.println("排序后：" + Arrays.toString(stuedents));
    }

    public static void main1(String[] args) {
        Stuedent stuedent1 = new Stuedent("lisi",11);
        Stuedent stuedent2 = new Stuedent("zhangsan",32);

        System.out.println(stuedent1.compareTo(stuedent2));
    }
}
